#include <CPCap>
#include <QLabel>
#include <QRubberBand>
#include <QMutex>
#include <tctracker.hpp>

#ifdef OPEN_GL
#include <QtOpenGL/QGLWidget>
#define WIDGET QGLWidget
#else
#define WIDGET QWidget
#endif

#include <QVariant>
#include <QSize>
#include <QMap>

struct QWebcamResolution {
    const char  *name;
    int         fourcc;
    int         width;
    int         height;
    int         index;
    int         size;
};

struct QWebcamFrameRate {
    int     fps;
    int     index;
};

typedef QList<QWebcamResolution> QWebcamResolutionList;
typedef QList<QWebcamFrameRate> QWebcamFrameRateList;
Q_DECLARE_METATYPE(QWebcamResolution)
Q_DECLARE_METATYPE(QWebcamFrameRate)

class QWebcam : public WIDGET 
{
	Q_OBJECT
public:
    QWebcam(QWidget *parent = 0);
    ~QWebcam();
    void                    setDevice(char *uid, char *name);
    void                    setResolution(QWebcamResolution info);
    QWebcamResolutionList   resolutionsList();
    QWebcamFrameRateList    framerateList(QWebcamResolution);
    void                    enableRGBTrace(bool);
    QImage                  capturedSelection();
    QImage                  capture();
    void                    setTracker(TCTracker *tracker);

public slots:
    void        selectArea(bool select);
    void        startTrackingSelectedArea();
    void        stopTracking();

protected:
    void    paintEvent(QPaintEvent *);
    void    mouseMoveEvent(QMouseEvent *);
    void    mousePressEvent(QMouseEvent *);
    void    mouseReleaseEvent(QMouseEvent *);
    void    leaveEvent(QEvent *);
    void    enterEvent(QEvent *);
    QSize   sizeHint() const;

private:
    QWebcamResolutionList m_Info;
    bool             m_TrackingActive;
    bool             m_SelectArea;
    QRect            m_Selection;
    QRubberBand     *m_RubberBand;
    bool             m_RGBTraceEnabled;
    CPCapDevice     *m_Device;
    unsigned char   *m_ImgData;
    QImage           m_Image;
    QLabel          *m_RgbLabel;
    int              m_RBx;
    int              m_RBy;
    QString          m_CurrentUid;
    QString          m_CurrentName;
    QMutex          *m_Mutex;
    QImage           m_Captured;
    TCTracker       *m_Tracker;

private slots:
    void  gotFrame(unsigned char *, int, int, int, int, unsigned int);

signals:
    void  areaSelected();
    void  trackingStoped();
    void  clicked(QColor);
};
